import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
// import { getToken } from '@/utils/token.js'

const Home = () => import('@/views/home/index.vue')
const Question = () => import('@/views/question/index.vue')
const Videos = () => import('@/views/videos/index.vue')

const User = () => import('@/views/user/index.vue')
const Chat = () => import('@/views/user/chat/index.vue')
const Profile = () => import('@/views/user/profile/index.vue')

const Login = () => import('@/views/login/index.vue')

const Article = () => import('@/views/article/index.vue')
const Tabbar = () => import('@/components/app-tabbar.vue')

Vue.use(VueRouter)

const routes = [
  {
    name: 'Home',
    path: '/home',
    components: {
      default: Home,
      bottom: Tabbar
    },
    alias: '/'
  },
  {
    name: 'Question',
    path: '/question',
    components: {
      default: Question,
      bottom: Tabbar
    }
  },
  {
    name: 'User',
    path: '/user',
    components: {
      default: User,
      bottom: Tabbar
    },
    meta: {
      needLogin: true
    }
  },
  {
    name: 'Videos',
    path: '/videos',
    components: {
      default: Videos,
      bottom: Tabbar
    }
  },
  {
    name: 'Article',
    path: '/article',
    component: Article
  },
  {
    name: 'Chat',
    path: '/user/chat',
    component: Chat,
    meta: {
      needLogin: true
    }
  },
  {
    name: 'Profile',
    path: '/user/profile',
    component: Profile,
    meta: {
      needLogin: true
    }
  },
  {
    name: 'Login',
    path: '/login',
    component: Login
  }
]

const router = new VueRouter({
  routes
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalPush.call(this, location, onResolve, onReject)
  }

  return originalPush.call(this, location).catch(err => err)
}

router.beforeEach((to, form, next) => {
  // console.log('state', store.state.user.Token)
  // console.log('getters', store.getters['user/getStateToken'])
  // console.log(store.state.user.Token)
  if (store.state.user.Token) {
    to.path.toLowerCase() === '/login' ? next('/') : next()
  } else {
    to.meta.needLogin ? next('/login') : next()
  }
})
router.afterEach((to, form, next) => {})

export default router
